import 'package:easydouban/bean/i_movie_favorite_entity.dart';
import 'package:easydouban/tools/circularTool.dart';
import 'package:easydouban/ui/movie_detail.dart';
import 'package:easydouban/ui/movie_item.dart';
import 'package:easydouban/viewModel/future_model.dart';
import 'package:flutter/material.dart';

import '../bean/i_top_entity.dart';

class SearchResultPage extends StatefulWidget {
  final String search;
  const SearchResultPage(this.search,{Key? key}) : super(key: key);

  @override
  State<SearchResultPage> createState() => _SearchResultPageState();
}

class _SearchResultPageState extends State<SearchResultPage> {
  
  Widget _buildFutureBuilder(BuildContext context, AsyncSnapshot<List<ITopEntity>?> snapshot){
    switch(snapshot.connectionState){
      case ConnectionState.none:
        return const Text('未开始网络请求...');
      case ConnectionState.active:
        return const Text('开始网络请求...');
      case ConnectionState.waiting:
        return const Center(child: CircularProgressIndicator());
      case ConnectionState.done:
        if(snapshot.hasError) {
          return const Center(child: Text('请求过于频繁,请稍后再试...'));
        }else{
          return Container(
             margin: const EdgeInsets.all(10.0),
             child: _buildMovieList(snapshot.data),
          );
        }
    }
  }

  ///构建搜索结果list列表
  Widget _buildMovieList(List<ITopEntity>? entityList){
    if(entityList == null || entityList.length == 0) return const Center(child: Text('没有搜索到相关内容!'));
    return ListView.builder(
        itemCount: entityList.length,
        itemBuilder: (BuildContext context, int index){
          return Container(
            padding: const EdgeInsets.all(10.0),
            child: MovieItem(
              MovieFavorite(
                  entityList[index].doubanId,
                  entityList[index].data[0].poster,
                  entityList[index].data[0].name,
                  entityList[index].data[0].country,
                  entityList[index].data[0].language,
                  entityList[index].data[0].genre,
                  entityList[index].data[0].description
              )
            ),
          );
        });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("搜索结果")),
      body: Container(
        child: FutureBuilder(
            future: getSearchList(widget.search), 
            builder: _buildFutureBuilder
        ),
      ),
    );
  }
}
